/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uit.ieproject.presentation;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import jvntokenizer.PennTokenizer;
import uit.ieproject.business.RegexBLO;
import uit.ieproject.entities.Regex;
import uit.ieproject.utilites.ImageUtil;
import uit.ieproject.utilites.Info;

/**
 *
 * @author Maivia
 */
public class ContentFileFrame extends javax.swing.JFrame {

    private String personName;
    private final int IMG_WIDTH;
    private final int IMG_HEIGHT;

    /**
     * Creates new form ContentFileFrame
     */
    public ContentFileFrame(String content, int typeImgString, String urlImage) {
        initComponents();

        //Center frame:
        this.setLocationRelativeTo(null);

        IMG_WIDTH = lbImage.getWidth();
        IMG_HEIGHT = lbImage.getHeight();

        personName = null;

        if (content != null) {
            taContent.setForeground(Color.blue);
            taContent.setText(content);  
            if (getNameFromContent(content) != null) {
                String name = getNameFromContent(content);
                lbName.setForeground(Color.blue);
                lbName.setText(name);
                taContent.setForeground(Color.blue);
            }
        }else{
            taContent.selectAll();
        }

        if (urlImage != null) {
            if (typeImgString == 0) {
                try {
                    BufferedImage img = ImageIO.read(new URL(urlImage));
                    Image resizedImage =
                            img.getScaledInstance(lbImage.getWidth(), lbImage.getHeight(), 0);
                    ImageIcon icon = new ImageIcon(resizedImage);
                    lbImage.setIcon(icon);
                } catch (Exception ex) {
                }
            } else {
                ImageUtil.showImage(lbImage, null, IMG_WIDTH, IMG_HEIGHT, urlImage);
            }
        } else {
            ImageUtil.showImage(lbImage, "default", IMG_WIDTH, IMG_HEIGHT, null);
        }
      
        taContent.setLineWrap(true);
        taContent.setWrapStyleWord(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btCancel = new javax.swing.JButton();
        btSave = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taContent = new javax.swing.JTextArea();
        lbImage = new javax.swing.JLabel();
        lbName = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nội dung văn bản");
        setResizable(false);

        btCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uit/ieproject/images/delete.gif"))); // NOI18N
        btCancel.setText("Thoát");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        btSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uit/ieproject/images/save24.png"))); // NOI18N
        btSave.setText("Lưu");
        btSave.setEnabled(false);
        btSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

        taContent.setColumns(20);
        taContent.setForeground(java.awt.Color.gray);
        taContent.setRows(5);
        taContent.setText("Sao chép và dán nội dung văn bản ở đây...");
        taContent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                taContentMousePressed(evt);
            }
        });
        taContent.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                taContentKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(taContent);

        lbImage.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

        lbName.setForeground(new java.awt.Color(255, 51, 51));
        lbName.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbName.setText("Không xác định");
        lbName.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lbName, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .addComponent(lbImage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbImage, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbName)
                        .addGap(0, 256, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSave, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSave, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed
        this.dispose();
        MainFrame currentMainFrame = (MainFrame) JFrame.getFrames()[1];
        String content = taContent.getText().trim();
        currentMainFrame.contentAddedFile = PennTokenizer.tokenize(content);
        currentMainFrame.lbAddFileWarning.setText("*Nội dung hợp lệ");
        currentMainFrame.lbAddFileWarning.setForeground(Color.blue);
        currentMainFrame.nameAddedFile = personName;
        if (currentMainFrame.tfDirStoreFile.getForeground() != Color.gray) {
            currentMainFrame.btFileAdd.setEnabled(true);
        }
        currentMainFrame.toFront();
    }//GEN-LAST:event_btSaveActionPerformed

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        this.dispose();
        MainFrame currentMainFrame = (MainFrame) JFrame.getFrames()[1];
        currentMainFrame.toFront();
    }//GEN-LAST:event_btCancelActionPerformed

    private void taContentMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taContentMousePressed
        JTextArea textarea = (JTextArea) evt.getSource();
        if (textarea.getForeground() == Color.gray || evt.getClickCount() == 2) {
            textarea.selectAll();
        }
    }//GEN-LAST:event_taContentMousePressed

    private void taContentKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_taContentKeyReleased
        JTextArea textarea = (JTextArea) evt.getSource();
        String content = textarea.getText().trim();
        content = PennTokenizer.tokenize(content);
        if (getNameFromContent(content) != null) {
            personName = getNameFromContent(content);
            lbName.setForeground(Color.blue);
            lbName.setText(personName);
            textarea.setForeground(Color.blue);
            btSave.setEnabled(true);
        } else {
            personName = null;
            lbName.setForeground(Color.red);
            lbName.setText(Info.NOT_MATCH_INFO);
            textarea.setForeground(Color.red);
            btSave.setEnabled(false);
        }
    }//GEN-LAST:event_taContentKeyReleased

    private String getNameFromContent(String content) {
        String name = null;
        try {
            RegexBLO regexBLO = new RegexBLO();

            ArrayList<Regex> regexs = regexBLO.getRegex(Info.NAME_REGEX, Info.EXTRACT_TYPE, 1);
            int size = regexs.size();
            for (int i = 0; i < size; i++) {
                Regex regex = regexs.get(i);
                String expression = regex.getExpression();
                Pattern pattern = Pattern.compile(expression);
                Matcher matcher = pattern.matcher(content);
                while (matcher.find()) {
                    if (matcher.group(Info.NAME_GROUP) != null) {
                        name = matcher.group(Info.NAME_GROUP).trim();
                        return name;
                    }
                }
            }
        } catch (SQLException ex) {
        }
        return name;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btSave;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbImage;
    private javax.swing.JLabel lbName;
    private javax.swing.JTextArea taContent;
    // End of variables declaration//GEN-END:variables
}
